package com.yuma.springshiroredisthymeleaf.config;

import com.yuma.springshiroredisthymeleaf.entity.Permission;
import com.yuma.springshiroredisthymeleaf.entity.Role;
import com.yuma.springshiroredisthymeleaf.entity.User;
import com.yuma.springshiroredisthymeleaf.service.PermissionService;
import com.yuma.springshiroredisthymeleaf.service.RoleService;
import com.yuma.springshiroredisthymeleaf.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

// Realm： 自定义的登录验证，和自定义的授权（都在数据库中）
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    private User loginUser;
    // 2.登录后的授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        // 1,根据登录的用户id获取所有的身份
        List<Role> roleList = roleService.getByUserId(loginUser.getUserId());
        // 2.循环添加角色给授权信息
        roleList.stream().forEach(role -> {
            // 添加角色
            simpleAuthorizationInfo.addRole(role.getRoleName());
            // 根据角色查询权限集合
            List<Permission> permissionList = permissionService.getByRoleId(role.getRoleId());
            // 3.循环添加权限给授权信息
            permissionList.stream()
                    .forEach(permission -> simpleAuthorizationInfo.addStringPermission(permission.getPerName()));
        });

        return simpleAuthorizationInfo;
    }

    // 1.登录验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 1.拿到token中用户名
        Object principal = authenticationToken.getPrincipal();

        // 2.根据用户名查询用户
        User user = userService.getByName(principal.toString());

        // 3.判断是否为空，不为空用户则创建AuthenticationInfo对象
        if (user != null) {
            loginUser = user;
            SimpleAuthenticationInfo simpleAuthenticationInfo =
                    new SimpleAuthenticationInfo(principal, user.getUserPwd(), "myRealm");
            return simpleAuthenticationInfo;
        }else {
            return null;
        }
    }
}
